package com.unbook.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unbook.entity.ResponseVo;
import com.unbook.entity.User;
import com.unbook.entity.params.UserInfoParam;
import com.unbook.service.IUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Null;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
@AllArgsConstructor
public class UserController {
    private final IUserService userService;

    @PutMapping("/saveInfo/{uId}")
    public ResponseVo<User> saveUserInfo(@PathVariable String uId, @RequestBody UserInfoParam param) {
        log.info(param.toString());
        User user = userService.saveUserInfo(uId, param);
        if (user != null)
            return ResponseVo.success(user);
        else
            return ResponseVo.error("用户基础信息保存失败");
    }

    @PutMapping("/disable/{uId}")
    public ResponseVo<Null> disableUser(@PathVariable String uId) {
        try {
            boolean isOk = userService.disable(uId);
            if (isOk)
                return ResponseVo.success(null);
            else
                return ResponseVo.error("禁用用户失败");
        } catch (Exception e) {
            return ResponseVo.error(e.getMessage());
        }
    }
    @PutMapping("/unDisable/{uId}")
    public ResponseVo<Null> unDisableUser(@PathVariable String uId) {
        try {
            boolean isOk = userService.unDisable(uId);
            if (isOk)
                return ResponseVo.success(null);
            else
                return ResponseVo.error("启用用户失败");
        } catch (Exception e) {
            return ResponseVo.error(e.getMessage());
        }
    }
    @GetMapping("/list")
    public ResponseVo<IPage<User>> userList(
        @RequestParam Long pageNum,
        @RequestParam Long pageSize,
        @RequestParam(required = false) String name,
        @RequestParam(required = false) Long phone
    ){
        LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>().lambda();
        if(name != null)
            queryWrapper.like(User::getName,name);
        if(phone != null)
            queryWrapper.like(User::getPhone, phone);
        return ResponseVo.success(userService.page(new Page<>(pageNum,pageSize), queryWrapper));
    }
}
